package com.assembler.app.genome;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.io.FileUtils;

/**
 * This class is responsible for I/O operations(saving/loading from file) with genome.
 * 
 * This class is a part of the lab rotation project for PhD  students in January 2014.
 * School of Computing
 * National University Singapore.
 * 
 * @author Iana Pyrogova, Abha Belorkar
 * @version 1.0.1
 */
public class GenomeFileHelper {

	public boolean saveToFile(String fileName, Genome genom) {
		try (FileOutputStream fout = new FileOutputStream(fileName, true);
				ObjectOutputStream oos = new ObjectOutputStream(fout);) {
			oos.writeObject(genom);
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public Genome readFromFile(String fileName) {
		try (FileInputStream streamIn = new FileInputStream(fileName);
				ObjectInputStream objectinputstream = new ObjectInputStream(
						streamIn)) {
			Genome result = (Genome) objectinputstream.readObject();
			return result;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public Genome readFromTxtFile(String fileName) {
		String genomAsString = null;
		String genomeStringAfterFormatting = null;
		try {
			genomAsString = FileUtils.readFileToString(new File(fileName));
			genomeStringAfterFormatting = genomAsString.replaceAll("[\n\r]", "");		   
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Genome(genomeStringAfterFormatting);
	}
}
